@using Composite.Core
@using Composite.Social.Instagram
@using Composite.Social.Instagram.Classes
@inherits RazorFunction

@functions {
    public override string FunctionDescription
    {
        get { return "Shows the most recent media published by a user."; }
    }

    [FunctionParameter(Label = "User Name", Help = "The User Name of the Instagram account.")]
    public string UserName { get; set; }

}
@{
    var FunctIdentificator = "user_recent_photos_" + UserName;

    var apiConfig = Data.Get<Composite.Social.Instagram.Data.Configuration>().FirstOrDefault();
    if (apiConfig == null)
    {
        <div class="alert alert-danger">Instagram Api Configuration is missing.</div>
        return;
    }

    InstagramResponse<InstagramMedia[]> response = null;
    try
    {
        var instagramConfig = new Configuration(null, apiConfig.ClientId, apiConfig.ClientSecret, null, null, "https://api.instagram.com/v1/", null);
        var api = InstagramApiWrapper.GetInstance(instagramConfig, new InstagramCache());

        var responseUser = api.UsersSearch(UserName, "100", null);
        if (responseUser == null)
        {
            <div class="alert alert-danger">Instagram User not found.</div>
            return;
        }
        var userId = "";
        foreach (var user in responseUser.data)
        {
            if (user.username == UserName)
            {
                userId = user.id;
                break;
            }
        }
        response = api.UserRecentMedia(userId, string.Empty, Request.QueryString["id"] == FunctIdentificator.GetHashCode().ToString() ? Request.QueryString["next"] : null, null, null, null, null);
    }
    catch (Exception ex)
    {
        Log.LogError("Composite.Social.Instagram.User.RecentPhotos", ex.Message);
    }
    if (response == null)
    {
        return;
    }
}
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:f="http://www.composite.net/ns/function/1.0">
<head>
</head>
<body>
    <div class="clearfix">
        @foreach (var photo in response.data)
        {
            <div class="pull-left">
                <a href="@photo.link" class="thumbnail">
                    <img src="@photo.images.thumbnail.url" alt="img" />
                </a>
            </div>
        }
    </div>
    @if (response.pagination != null && !string.IsNullOrEmpty(response.pagination.next_max_id))
    {
        <a class="btn btn-default btn-sm" href="?next=@response.pagination.next_max_id&amp;id=@FunctIdentificator.GetHashCode()">@Resources.Instagram.ViewMore_Text</a>
    }
</body>
</html>